package com.lzy.algorithm;

import java.util.List;

public class N个有序链表合并 {

    public static void main(String[] args) {
        ListNode l1 = new ListNode(7);
        l1.next = new ListNode(33);
        l1.next.next = new ListNode(56);

        ListNode l2 = new ListNode(6);
        l2.next = new ListNode(23);
        l2.next.next = new ListNode(88);
        l2.next.next.next = new ListNode(101);

        ListNode l3 = new ListNode(1);
        l3.next = new ListNode(16);
        l3.next.next = new ListNode(55);

        ListNode[] listNodes = new ListNode[]{l1, l2, l3};

        //ListNode result = mergeNodeForNByDG(listNodes, 0, listNodes.length - 1);
        ListNode result = mergeNodeForN(listNodes);

        while (result != null) {
            System.out.println(result.val);
            result = result.next;
        }
    }

    public static ListNode mergeNodeForNByDG(ListNode[] listNodes, int left, int right) {
        if (left >= right) {
            return listNodes[left];
        }
        int mid = (left + right) / 2;
        ListNode l1 = mergeNodeForNByDG(listNodes, left, mid);
        ListNode l2 = mergeNodeForNByDG(listNodes, mid + 1, right);
        return mergeNode(l1, l2);
    }

    public static ListNode mergeNodeForN(ListNode[] listNodes) {

        int n = listNodes.length;
        while (n > 1) {
            int idx = 0;

            for (int i = 0; i < n; i = i + 2) {
                if (i == n - 1) {
                    listNodes[idx++] = listNodes[i];
                } else {
                    listNodes[idx++] = mergeNode(listNodes[i], listNodes[i + 1]);
                }
            }
            n = idx;
        }

        return listNodes[0];
    }

    public static ListNode mergeNode(ListNode l1, ListNode l2) {
        ListNode head = new ListNode(-1);
        ListNode node = head;
        while (l1 != null && l2 != null) {
            if (l1.val <= l2.val) {
                node.next = l1;
                l1 = l1.next;
            } else {
                node.next = l2;
                l2 = l2.next;
            }
            node = node.next;
        }

        node.next = l1 == null ? l2 : l1;

        return head.next;
    }
}
